//
//  CloudCall.m
//  cloudCall
//
//  Created by zhang on 2021/10/29.
//

#import "CFCloudCall.h"
#import "QTBClientCallCore.h"
#import "CallNumberViewController.h"
#import <CloudCallBaseFrame/CommonFrame.h>
#import "ReceiveCallHeaderView.h"
#import "CallingNoteView.h"
#import "LCPatientModel.h"

@interface CFCloudCall () <QTBClientCallSessionInDelegate>

/** 原生调用h5*/
@property (nonatomic, strong)CDVInvokedUrlCommand *command;
//@property (nonatomic, strong)CDVPluginResult *pluginResult;
@property (nonatomic, strong)CallingNoteView *noteView;
/// 当前通话患者
@property (nonatomic, strong)LCPatientModel *currentPatient;
/**配置信息*/
@property (nonatomic, strong)LCBaseConfigModel *baseModel;

@property (nonatomic, strong)LCWebViewController *webController;

@end


@implementation CFCloudCall


- (void)pluginInitialize {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nativeClickAction:) name:NativeClickActionNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setCurrentPatientAction:) name:SetCurrentPatientNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endAction) name:CallingDidEndNotification object:nil];
    self.noteView = [[CallingNoteView alloc] init];
    INBWeakSelf;
    self.noteView.clickBlock = ^{
        INBStrongSelf;
        [self presentDetail];
    };
}

- (void)nativeCallBackAction:(CDVInvokedUrlCommand *)command {
    self.command = command;
}

-(void)nativeClickAction:(NSNotification*)sender{
    if (self.webController) {
        [self.webController dismissViewControllerAnimated:YES completion:nil];
    }
    LCPatientActionModel *actionItem = sender.object;
    if ([actionItem isKindOfClass:[LCPatientActionModel class]]) {
        /// 传递原生事件给h5
        NSMutableDictionary *data = [actionItem.eventData mutableCopy];
        data[@"patient"] = self.currentPatient.dictionaryValue;
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self jsonStringCompactFormatForDictionary:data]];
        [pluginResult setKeepCallbackAsBool:YES];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:self.command.callbackId];
    }
}

-(void)setCurrentPatientAction:(NSNotification*)sender{
    LCPatientModel *patient = sender.object;
    if ([patient isKindOfClass:[LCPatientModel class]]) {
        self.currentPatient = patient;
    }
}

-(void)endAction{
    self.currentPatient = nil;
}

/// h5调用原生方法
- (void)cloudCallNativeServer:(CDVInvokedUrlCommand *)command {
    [self.commandDelegate runInBackground:^{
        if (command.arguments.count == 0) {
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"没有参数"]];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return;
        }
        NSString *action = command.arguments[0];
        if ([action isKindOfClass:[NSString class]]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([action isEqualToString:@"loginServer"]) {
                    if (command.arguments.count > 1 && [command.arguments[1] isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *account = command.arguments[1];
                        self.baseModel = [LCBaseConfigModel modelWithDictionary:account];
                        [self loginServer:command];
                    } else {
                        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"数据异常"]];
                        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                    }
                    return;
                }
                /// 拨打电话
                if ([action isEqualToString:@"callPatients"]) {
                    [self callPatients:command];
                    return;
                }
                /// 跳转云呼列表
                if ([action isEqualToString:@"cloudCallListInfo"]) {
                    [self cloudCallWebView:command];
                    return;
                }
                /// 登出云呼
                if ([action isEqualToString:@"logoutServer"]) {
                    [self cloudCallLogout:command];
                    return;
                }
            });
        }
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"暂不支持"]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}




- (void)loginServer:(CDVInvokedUrlCommand *)command {
    if (!self.baseModel) {
        [MBProgressHUD showMessage:@"缺少坐席信息"];
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"数据异常"]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    if (self.baseModel.checkClinicOpenAccount && self.baseModel.checkTenantOpenAccount && self.baseModel.account.length) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"是否登录坐席？" message:@"确认登录当前设备后，其他设备上已登录账号将被自动踢出" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[QTBClientCallCore shareCallCore] setCallSessionInDelegate:self];
            LoginInfo *info = [[QtbClient shareClient] getLoginInfo];
            if (info.account) {
                CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"登录成功"];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                return;
            }
            NSString *centerHost = self.baseModel.callServerUrl;
            NSString *name = self.baseModel.account;
            NSString *password = self.baseModel.password;
            [[QTBClientCallCore shareCallCore] login:name password:password type:1 host:centerHost completion:^(int code, NSString *msg) {
                if (code == 0) {
                    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"登录成功"];
                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                }else {
                    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:[NSString stringWithFormat:@"登录失败:%@",msg]]];
                    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
                    [MBProgressHUD showMessage:msg];
                }
            }];
        }];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"取消登录"]];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }];
        [alertVC addAction:action1];
        [alertVC addAction:action];
        [self.viewController presentViewController:alertVC animated:YES completion:nil];
    } else {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"缺少坐席信息"]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}


-(void)setBaseModel:(LCBaseConfigModel *)baseModel {
    _baseModel = baseModel;
    [WWPortManagerTool defaultTool].actionArray = baseModel.actionItems;
    NSString *host = baseModel.apiServerUrl;
    [LCRequester sharedForApp].baseUrl = [NSURL URLWithString:host];
    [[LCRequester sharedForApp].afManager.requestSerializer setValue:baseModel.user.saasToken forHTTPHeaderField:KEY_TOKEN];
    [[LCRequester sharedForApp].afManager.requestSerializer setValue:baseModel.user.env forHTTPHeaderField:@"env"];
    [[LCRequester sharedForApp].afManager.requestSerializer setValue:@"backTenant" forHTTPHeaderField:@"platform"];
}

- (void)callPatients:(CDVInvokedUrlCommand *)command {
    if (command.arguments.count < 2) {
        /// 末登陆
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"参数错误"]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    NSDictionary *patient = command.arguments[1];
    if (![patient isKindOfClass:[NSDictionary class]]) {
        /// 患者信息异常
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"患者信息异常"]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        return;
    }
    LoginInfo *info = [[QtbClient shareClient] getLoginInfo];
    if (info.account) {
        INBWeakSelf;
        LCPatientModel *item = [LCPatientModel modelWithDictionary:patient];
        if (!item.phone.length) {
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"缺少电话号"]];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            return;
        }
        NSArray<LCPatientModel *> *dataArray = (NSArray<LCPatientModel *> *)@[item];
        if (dataArray.count) {
            [WWPortManagerTool defaultTool].patientsArray = dataArray;
            [[NSNotificationCenter defaultCenter] postNotificationName:GetPatientsInfoNotification object:nil];
        }
        [[QTBClientCallCore shareCallCore] startCallPhone:item.phone completion:^(int code, NSString *msg, QTBClientCallSession *callSession) {
            INBStrongSelf;
            if (code == 0) { /// 拨号成功
                [self presentDetail];
                CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self getCallBackMessage:command Meaage:[NSString stringWithFormat:@"拨号成功:%@",msg]]];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            } else {
                CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:[NSString stringWithFormat:@"拨号失败:%@",msg]]];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
            }
        }];
    } else {
        /// 末登陆
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[self getCallBackMessage:command Meaage:@"需要先登陆云呼"]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        [self dealUnLogin];
    }
}


-(void)cloudCallLogout:(CDVInvokedUrlCommand *)command {
    [[QTBClientCallCore shareCallCore] logout:^(int code, NSString * _Nonnull msg) {
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"登出成功"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}


-(void)cloudCallWebView:(CDVInvokedUrlCommand *)command {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        LCWebViewController *vc = [[LCWebViewController alloc] init];
        NSMutableDictionary *dict = [self.baseModel.user.dictionaryValue mutableCopy];
        if (command.arguments.count>1 && [command.arguments[1] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *patient = command.arguments[1];
            if (patient[@"id"]) {
                dict[@"customerId"] = patient[@"id"];
            }
        }
        dict[@"cloudCallAccount"] = self.baseModel.account ?: @"";
        vc.userData = dict;
        NSString *url = self.baseModel.callRecordsH5Url;
        vc.url = [NSURL URLWithString:url];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        if (nav.modalPresentationStyle != UIModalPresentationCustom) {
            nav.modalPresentationStyle = UIModalPresentationFullScreen;
        }
        self.webController = vc;
        INBWeakSelf;
        vc.callBlock = ^(NSDictionary *dict) {
            INBStrongSelf;
            NSString *methord = dict[@"method"];
            if (!methord) {
                return;
            }
            if ([methord isEqualToString:@"toCall"]) {
                NSDictionary *info = dict[@"data"];
                [self webCallPatient:info];
            } else if ([methord isEqualToString:@"toCustomerDetails"]) {
                NSDictionary *info = dict[@"data"];
                [self openPatientDetail:info];
                self.webController = nil;
            }
        };
        [self.viewController presentViewController:nav animated:YES completion:nil];
    });
}

-(void)webCallPatient:(NSDictionary *)data{
    LCPatientModel *item = [LCPatientModel modelWithDictionary:data];
    if (!item.phone.length) {
        [MBProgressHUD showMessage:@"数据异常"];
        return;
    }
    if (data[@"gender"]) {
        NSNumber *gender = data[@"gender"];
        if([gender intValue] == 1) {
            item.gender = @"M";
        } else if([gender intValue] == 2) {
            item.gender = @"F";
        }
    }
    LoginInfo *info = [[QtbClient shareClient] getLoginInfo];
    if (info.account) {
        INBWeakSelf;
        if (item.id && item.id.length) {
            NSArray<LCPatientModel *> *dataArray = (NSArray<LCPatientModel *> *)@[item];
            if (dataArray.count) {
                [WWPortManagerTool defaultTool].patientsArray = dataArray;
                [[NSNotificationCenter defaultCenter] postNotificationName:GetPatientsInfoNotification object:nil];
            }
        }
        [QTBClientCallCore shareCallCore].currentCall.identifier = item.phone;
        [[QTBClientCallCore shareCallCore] startCallPhone:item.phone completion:^(int code, NSString *msg, QTBClientCallSession *callSession) {
            INBStrongSelf;
            if (code == 0) { /// 拨号成功
                [self presentDetail];
            } else {
                [MBProgressHUD showMessage:[NSString stringWithFormat:@"拨号失败:%@",msg]];
            }
        }];
    } else {
        [self dealUnLogin];
    }
}

-(void)dealUnLogin{
    if (!self.baseModel.autoLogin) { return; }
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"是否登录坐席？" message:@"确认登录当前设备后，其他设备上已登录账号将被自动踢出" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *centerHost = self.baseModel.callServerUrl;
        NSString *name = self.baseModel.account;
        NSString *password = self.baseModel.password;
        [[QTBClientCallCore shareCallCore] login:name password:password type:1 host:centerHost completion:^(int code, NSString *msg) {
            if (code == 0) {
                [MBProgressHUD showMessage:@"登陆成功"];
            }else {
                [MBProgressHUD showMessage:msg];
            }
        }];
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertVC addAction:action1];
    [alertVC addAction:action];
    [self.viewController presentViewController:alertVC animated:YES completion:nil];
}

-(void)openPatientDetail:(NSDictionary *)data{
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result[@"name"] = @"patientDetail";
    result[@"patient"] = data;
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[self jsonStringCompactFormatForDictionary:result]];
    [pluginResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:self.command.callbackId];
}

-(void)presentDetail{
    dispatch_async(dispatch_get_main_queue(), ^{
        CallNumberViewController *vc = [[CallNumberViewController alloc] init];
        if (vc.modalPresentationStyle != UIModalPresentationCustom) {
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
        }
        INBWeakSelf;
        vc.shrinkBlock = ^{
            INBStrongSelf;
            [self.noteView showView];
        };
        [[self getCurrentVC] presentViewController:vc animated:YES completion:nil];
    });
}

/// 收到来电
-(void)onCallIn:(QTBClientCallSession *)callSession {
    NSString *number = callSession.identifier;
    //    ReceiveCallHeaderView *call = [[ReceiveCallHeaderView alloc] init];
    //    call.acount = number;
    //    [call showView];
    //    INBWeakSelf;
    //    call.clickBlock = ^{
    //        INBStrongSelf;
    //        [self presentDetail];
    //    };
//    if ([[self getCurrentVC] isKindOfClass:[CallNumberViewController class]]) {
//        return;
//    }
    [WWPortManagerTool defaultTool].isRequest = NO;
    [self getPatientInfo:number];
    [self presentDetail];
}

-(void)getPatientInfo:(NSString *)number{
    if (!number.length) {
        return;
    }
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    dict[@"phone"] = number;
    NSString *url = [NSString stringWithFormat:@"%@/ccc/api/v1/customer/app/customer-info",self.baseModel.apiServerUrl];
    [[LCRequester sharedForApp] requestWithMethod:HTTP_POST urlString:url parameters:dict finish:^(NSURLSessionDataTask *operation, id responseObject, NSError *error) {
        if (responseObject && [responseObject isKindOfClass:[NSDictionary class]] && responseObject[@"body"] && responseObject[@"body"][@"content"]) {
            NSArray *datas = responseObject[@"body"][@"content"];
            NSArray *models = [LCSCRMPatientModel modelsWithArray:datas];
            NSMutableArray *patients = [[NSMutableArray alloc] init];
            for (LCSCRMPatientModel *item in models) {
                LCPatientModel *model = [[LCPatientModel alloc] init];
                model.id = item.customerId;
                model.name = item.customerName;
                model.gender = @"";
                if (item.gender == 1) {
                    model.gender = @"M";
                } else if (item.gender == 2) {
                    model.gender = @"F";
                }
                model.age = item.age;
                model.phone = number;
                model.birthDate = item.birthday;
                model.avatarUrl = item.customerImgUrl;
                model.emrNo = item.customerNumber;
                [patients addObject:model];
            }
            if (models.count) {
                [WWPortManagerTool defaultTool].patientsArray = patients;
            }
        }
        [WWPortManagerTool defaultTool].isRequest = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:GetPatientsInfoNotification object:nil];
    }];
}


-(NSString *)getCallBackMessage:(CDVInvokedUrlCommand *)command Meaage:(NSString *)mesage{
    NSArray *data = command.arguments;
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    for (id item in data) {
        if ([item isKindOfClass:[NSDictionary class]]) {
            [resultArray addObject:[self jsonStringCompactFormatForDictionary:(NSDictionary *)item]];
        } else {
            [resultArray addObject:item];
        }
    }
    return [NSString stringWithFormat:@"%@  参数: %@",mesage,[self jsonStringCompactFormatForNSArray:resultArray]];
}


- (NSString *)jsonStringCompactFormatForDictionary:(NSDictionary *)dicJson {
    if (![dicJson isKindOfClass:[NSDictionary class]] || ![NSJSONSerialization isValidJSONObject:dicJson]) {
        return @"";
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:0 error:nil];
    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;
}


//将数组转换成json格式字符串,不含\n这些符号
- (NSString *)jsonStringCompactFormatForNSArray:(NSArray *)arrJson {
    if (![arrJson isKindOfClass:[NSArray class]] || ![NSJSONSerialization isValidJSONObject:arrJson]) {
        return @"";
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrJson options:0 error:nil];
    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;
}


@end
